import { setRoleStatus } from '@/api/system/role';
import { VxeGridPropTypes } from '@/components/VxeTable';
import { hasPermission } from '@/utils/permission';
import { Switch, message } from 'ant-design-vue';
import { EleTag } from 'ele-admin-pro';
import { h } from 'vue';

export default [
  {
    type: 'checkbox',
    width: 35
  },
  {
    title: '角色名称',
    field: 'name'
  },
  {
    title: '编码',
    field: 'code'
  },
  {
    title: '状态',
    field: 'status',
    slots: {
      default: ({ row }) => {
        if (!Reflect.has(row, 'pendingStatus')) {
          row.pendingStatus = false;
        }
        return h(Switch, {
          checked: row.status === 1,
          checkedChildren: '已启用',
          unCheckedChildren: '已禁用',
          disabled: !hasPermission('sysRole:setStatus'),
          loading: row.pendingStatus,
          onChange(checked: boolean) {
            row.pendingStatus = true;
            const newStatus = checked ? 1 : 2;
            setRoleStatus(row.id, newStatus)
              .then(() => {
                row.status = newStatus;
                message.success(`已成功修改角色状态`);
              })
              .catch(() => {
                message.error('修改角色状态失败');
              })
              .finally(() => {
                row.pendingStatus = false;
              });
          }
        });
      }
    }
  },
  {
    title: '数据范围',
    field: 'dataScope',
    slots: {
      default: ({ row }) => {
        const dataScope = row.dataScope;
        switch (dataScope) {
          case 1:
            return h(EleTag, { color: 'orange' }, () => '全部数据');
          case 2:
            return h(EleTag, { color: 'orange' }, () => '本部门及以下');
          case 3:
            return h(EleTag, { color: 'orange' }, () => '本部门数据');
          case 4:
            return h(EleTag, { color: 'orange' }, () => '仅本人数据');
          case 5:
            return h(EleTag, { color: 'orange' }, () => '自定义数据');
        }
        return dataScope;
      }
    }
  },
  {
    title: '排序',
    field: 'order'
  },
  {
    title: '备注',
    field: 'remark',
    width: 90
  },
  {
    title: '创建时间',
    field: 'createTime',
    visible: false
  },
  {
    width: 140,
    title: '操作',
    align: 'center',
    slots: { default: 'action' },
    fixed: 'right'
  }
] as VxeGridPropTypes.Columns;
